package com.spring.hot;

/**
 * @author Cizai
 * @since 2022/12/01 19:25
 * @see <a href="https://leetcode.cn/problems/string-to-integer-atoi/description/">...</a>
 **/
public class 字符串转换整数 {

    public int myAtoi(String s) {

        boolean flag = false;
        boolean flagK = false;
        char[] array = s.toCharArray();

        int i = 0;
        for (char c : array) {
            if (c != ' ') break;
            i++;
        }

        if(i == s.length()) return 0;
        if (array[i] == '-'){
            flag = true;i++;
        }
        if(i == s.length()) return 0;
        if (array[i] == '+'){
            i++;
            flagK = true;
        }
        if(flagK && flag) return 0;

        int sum = 0;
        for(int j = i; j < array.length; j++) {
            if (!Character.isDigit(array[j])) return flag ? -sum : sum;

            if (sum > (Integer.MAX_VALUE-(array[j]-'0'))/10) {
                return flag ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            sum = sum*10+(array[j]-'0');
        }
        return flag ? -sum : sum;

    }
}
